package com.vrv.netmgr.strategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.common.util.JsonUtil;
import com.vrv.netmgr.R;
import com.vrv.netmgr.strategy.detail.DetailPrevIllExtConnActivity;
import com.vrv.netmgr.vo.SerializablePrevIllExtConn;

/**
 * @Description 防违规外联策略
 * @author gaopei
 * @date
 *
 */
@SuppressLint("HandlerLeak")
public class PrevIllExtConnActivity extends Activity {

	// 存储数据的数组列表
	private ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
	private ListView listView;
	private ListAdapter adapter = new ListAdapter();
	private String STRATEGY_ID;
	private String STRATEGY_NAME;
	private String STRATEGY_OBJ;
	private String STRATEGY_STATE;
	private String CREATE_USER;
	private String CHG_PERMISS;
	// 查询到的记录总数
	private int RECORD_COUNT;
	// 当前页号，从0开始算
	private int CUR_INDEX;
	// 通过点击按钮查询标记
	@SuppressWarnings("unused")
	private boolean qryByBtnFlag = false;
	// 列表的页脚视图
	private View loadMoreView;
	// 异常判断标记
	private boolean retVal;
	/**
	 * 等待对话框
	 */
	private ProgressDialog progressDialog;
	/**
	 * 查询
	 */
	private static final int BACK_NULL = 2;
	private static final int QUERY = 3;
	private static final int NET_ERR = 4;
	private static final int QUERY_BY_POLICY_NAME = 5;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.assets_list_page);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		init();
		progressDialog = ProgressDialog.show(PrevIllExtConnActivity.this, "", "查询中...", true, true);

		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer(0, false, null);
				if (!retVal){
					handler.sendEmptyMessage(NET_ERR);
				}else{
					if (null == listData || 0 == listData.size()) {
						handler.sendEmptyMessage(BACK_NULL);
					} else {
						handler.sendEmptyMessage(QUERY);
					}
				}
			}
		}).start();
	}

	private void init() {
		setTitle();
		STRATEGY_ID = this.getString(R.string.strat_id);
		STRATEGY_NAME = this.getString(R.string.strat_name);
		STRATEGY_OBJ = this.getString(R.string.strat_obj);
		STRATEGY_STATE = this.getString(R.string.strat_stat);
		CREATE_USER = this.getString(R.string.create_user);
		CHG_PERMISS = this.getString(R.string.chg_permiss);

		listBackView = (LinearLayout) findViewById(R.id.list_background);
	}

	/** listview背景设置 */
	private LinearLayout listBackView;

	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY:
				findViews();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case QUERY_BY_POLICY_NAME:
				qryByBtnFlag = true;
				if (RECORD_COUNT > 0) {
					listView.removeFooterView(loadMoreView);
					listView.setVisibility(View.VISIBLE);
					if (RECORD_COUNT > ListViewUtil.PAGESIZE) {
						String policyName = msg.getData().getString("policyName");
						loadMorePage(true, policyName);
					}
					initializeAdapter();
					adapter.notifyDataSetChanged();
				} else
					listView.setVisibility(View.GONE);
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case NET_ERR:
				Toast.makeText(PrevIllExtConnActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
				onBackPressed();
				break;
			case BACK_NULL:
				Toast.makeText(PrevIllExtConnActivity.this, "数据为空", Toast.LENGTH_LONG).show();
				onBackPressed();
				break;
			}
		}
	};

	public void setTitle() {
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText("防违规外联策略");

		/**
		 * 返回按钮
		 */
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setVisibility(View.VISIBLE);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
	}

	public void findViews() {
		if (listView == null) {
			// 搜索输入框
			EditText edit = (EditText) findViewById(R.id.assets_conditionQry);
			// 搜索按钮
			ImageView search_btn = (ImageView) findViewById(R.id.search_go_btn);
			edit.setHint(R.string.input_policy_name);
			// edit.addTextChangedListener(new MyTextWatcher(edit, search_btn));
			search_btn.setOnClickListener(new ClickSearchBtnListener(edit, search_btn));
			listView = (ListView) findViewById(R.id.assets_lv_id);
		}
		if (RECORD_COUNT > 0) {
			listView.setVisibility(View.VISIBLE);
			if (RECORD_COUNT > ListViewUtil.PAGESIZE)
				loadMorePage(false, null);
			initializeAdapter();
			if (listView.getAdapter() == null)
				listView.setAdapter(adapter);
			else
				adapter.notifyDataSetChanged();
			listView.setOnItemClickListener(new ListViewItemClick());
		}
	}

	private class ClickSearchBtnListener implements View.OnClickListener {
		EditText edit;
		ImageView search_btn;

		ClickSearchBtnListener(EditText edit, ImageView search_btn) {
			this.edit = edit;
			this.search_btn = search_btn;
		}

		@Override
		public void onClick(View v) {
			final String editVal = edit.getText().toString();
			listData.clear();
			adapter.clear();
			progressDialog = ProgressDialog.show(PrevIllExtConnActivity.this, "", "查询中...", true, true);
			search_btn.setEnabled(false);
			new Handler().post(new Runnable() {
				@Override
				public void run() {
					getDataFromServer(0, true, editVal);
					Message msg = new Message();
					msg.what = QUERY_BY_POLICY_NAME;
					Bundle data = new Bundle();
					data.putString("policyName", editVal);
					msg.setData(data);
					handler.sendMessage(msg);
					search_btn.setEnabled(true);
				}
			});
		}
	}

	// private class MyTextWatcher implements TextWatcher{
	// EditText edit;
	// ImageButton search_btn;
	//
	// MyTextWatcher(EditText edit, ImageButton search_btn){
	// this.edit = edit;
	// this.search_btn = search_btn;
	// }
	//
	// @Override
	// public void afterTextChanged(Editable s) {
	// String editVal = edit.getText().toString().trim();
	// if(StringUtils.isNotBlank(editVal))
	// search_btn.setVisibility(View.VISIBLE);
	// else {
	// search_btn.setVisibility(View.GONE);
	// if(qryByBtnFlag){
	// qryByBtnFlag = false;
	// listData.clear();
	// adapter.clear();
	// progressDialog = ProgressDialog.show(PrevIllExtConnActivity.this, "",
	// "查询中...", true, true);
	//
	// new Thread(new Runnable() {
	// @Override
	// public void run() {
	// getDataFromServer(0, false, null);
	// handler.sendEmptyMessage(QUERY);
	// }
	// }).start();
	// }
	// }
	// }
	//
	// @Override
	// public void beforeTextChanged(CharSequence s, int start, int count,
	// int after) {
	//
	// }
	//
	// @Override
	// public void onTextChanged(CharSequence s, int start, int before,
	// int count) {
	//
	// }
	//
	// }

	// 查询所有数据
	public void getDataFromServer(int pageNum, boolean byPolicyName, String PolicyName) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(GlobalConstants.PAGE_NUM, pageNum + "");
		map.put(GlobalConstants.POLICYFUNC, "ONLINE-DEAL-CONTROL");
		if (byPolicyName)
			map.put(GlobalConstants.POLICY_NAME, PolicyName);
		retVal = qryPolicy(map);
	}

	public boolean qryPolicy(Map<String, String> map) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
		String urlAddr = urlPrefix + "/policy/jsonList.do";
		String response = httpClientToServer.doPost(urlAddr, map);

		if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");
			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");
			RECORD_COUNT = count;
			if (count < 1)
				return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			int jArrLen = jArr.length();
			if (jArrLen > 0)
				CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				HashMap<String, Object> myMap = new HashMap<String, Object>();
				myMap.put(STRATEGY_ID, JsonUtil.getJsonString(jObj, "policyId"));
				myMap.put(STRATEGY_NAME, JsonUtil.getJsonString(jObj, GlobalConstants.POLICY_NAME));
				myMap.put(STRATEGY_OBJ, JsonUtil.getJsonString(jObj, "policyObject"));
				String useFlag = JsonUtil.getJsonString(jObj, "policyStart");
				myMap.put(STRATEGY_STATE, "1".equals(useFlag) ? "启用" : "停用");
				myMap.put(CREATE_USER, ("所属:" + JsonUtil.getJsonString(jObj, "policyCreateUser") + "\n修改:" + JsonUtil.getJsonString(jObj, "policyModifyUser")).replace('$', ' '));
				String modifyRight = JsonUtil.getJsonString(jObj, "reserved7");
				myMap.put(CHG_PERMISS, "private".equals(modifyRight) ? "私有" : "公有");
				listData.add(myMap);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	/**
	 * 初始化ListView的适配器
	 */
	public void initializeAdapter() {

		for (int i = 0; i < listData.size(); i++)
			adapter.addItem(listData.get(i));
	}

	/*
	 * 加载更多数据
	 */
	private void loadMoreData(boolean pageDown, boolean byPolicyName, String policyName) {
		int index;
		if (pageDown)
			index = CUR_INDEX + 1;
		else
			index = CUR_INDEX - 1;
		listData.clear();
		adapter.clear();
		getDataFromServer(index, byPolicyName, policyName);
		int datasize = listData.size();
		for (int i = 0; i < datasize; i++)
			adapter.addItem(listData.get(i));
	}

	public void loadMorePage(final boolean byPolicyName, final String policyName) {
		loadMoreView = getLayoutInflater().inflate(R.layout.list_page_load, null);
		final Button loadNextButton = (Button) loadMoreView.findViewById(R.id.loadNextButton);
		final Button loadPreButton = (Button) loadMoreView.findViewById(R.id.loadPreButton);
		loadNextButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadNextButton.getText().equals("查看下一页")) {
					loadNextButton.setText("正在加载中..."); // 设置按钮文字
					loadNextButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(true, byPolicyName, policyName);
							adapter.notifyDataSetChanged();
							loadNextButton.setText("查看下一页"); // 恢复按钮文字
							if ((CUR_INDEX + 1) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.GONE);
							if (CUR_INDEX == 1)
								loadPreButton.setVisibility(View.VISIBLE);
							loadNextButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		loadPreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadPreButton.getText().equals("查看上一页")) {
					loadPreButton.setText("正在加载中..."); // 设置按钮文字
					loadPreButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(false, byPolicyName, policyName);
							adapter.notifyDataSetChanged();
							loadPreButton.setText("查看上一页"); // 恢复按钮文字
							if (CUR_INDEX == 0)
								loadPreButton.setVisibility(View.GONE);
							if ((CUR_INDEX + 2) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.VISIBLE);
							loadPreButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		listView.addFooterView(loadMoreView); // 设置列表底部视图

	}

	private class ListViewItemClick implements AdapterView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			HashMap<String, Object> hashMap = adapter.getData(arg2);
			//
			SerializablePrevIllExtConn serializable = new SerializablePrevIllExtConn();
			serializable.setSTRATEGY_ID(hashMap.get(STRATEGY_ID).toString());
			serializable.setSTRATEGY_NAME(hashMap.get(STRATEGY_NAME).toString());
			serializable.setSTRATEGY_OBJ(hashMap.get(STRATEGY_OBJ).toString());
			serializable.setSTRATEGY_STATE(hashMap.get(STRATEGY_STATE).toString());
			serializable.setCREATE_USER(hashMap.get(CREATE_USER).toString());
			serializable.setCHG_PERMISS(hashMap.get(CHG_PERMISS).toString());
			//
			Intent intent = new Intent(PrevIllExtConnActivity.this, DetailPrevIllExtConnActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("info", serializable);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}

	private class ListAdapter extends ListViewAdapter {
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final HashMap<String, Object> hashMap = getData(position);
			if (view == null) {
				view = LayoutInflater.from(PrevIllExtConnActivity.this).inflate(R.layout.previllextconn_listpage_item, null);
			}
			/** 默认背景色设置 */
			view.setBackgroundResource(R.drawable.list_item_state1);
			/** 双行背景色设置 */
			if (position % 2 == 0) {
				view.setBackgroundResource(R.drawable.list_item_state);
			}

			TextView tv1 = (TextView) view.findViewById(R.id.tv_depname);
			TextView tv2 = (TextView) view.findViewById(R.id.tv_devip);
			TextView tv3 = (TextView) view.findViewById(R.id.tv_limit);
			tv1.setText(hashMap.get(STRATEGY_NAME).toString());
			tv2.setText(hashMap.get(STRATEGY_STATE).toString());
			tv3.setText(hashMap.get(CHG_PERMISS).toString());
			return view;
		}
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
